package de.herberlin.contact;

import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

/**
 * The Class Manager. Provides logger and xml-parser access.
 */
public abstract class Manager {

	/** The Constant PATH. */
	public static final String PATH = "/logging.properties";

	/**
	 * Configure logging. Should be called when application starts.
	 */
	public static void configureLogging() {
		try {
			LogManager.getLogManager().readConfiguration(
					Manager.class.getResourceAsStream(PATH));
		} catch (Exception e) {
			e.printStackTrace();
			getLogger(Manager.class).log(Level.SEVERE,"Error reading: " + PATH, e);
		}
	}

	/** The _xpath. */
	private static XPath _xpath = null;

	/**
	 * Gets the xpath parser.
	 * 
	 * @return the parser
	 */
	public static XPath getParser() {
		if (_xpath == null) {
			_xpath = XPathFactory.newInstance().newXPath();
			getLogger(Manager.class).log(Level.FINE,"DocumentBuilder created:" + _docBuilder);
		}
		return _xpath;
	}
	
	/** The _doc builder. */
	private static DocumentBuilder _docBuilder=null;
	
	/**
	 * Gets the document builder.
	 * 
	 * @return the document builder
	 * 
	 * @throws Exception the exception
	 */
	public static DocumentBuilder getDocumentBuilder() throws Exception {
		if (_docBuilder==null) {
			try {
				_docBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
				getLogger(Manager.class).log(Level.FINE,"DocumentBuilder created:" + _docBuilder);
			} catch (Exception e) {
				Manager.getLogger(Manager.class).log(Level.SEVERE,"Error Creating Document Builder: "+e,e);
				throw e;
			}
		}
		return _docBuilder;
	}
	
	/**
	 * Gets the logger.
	 * 
	 * @param obj the obj as logging source
	 * 
	 * @return the logger
	 */
	@SuppressWarnings("unchecked")
	public static Logger getLogger(Object obj) {
		String loggerName=null;
		if (obj==null) {
			loggerName="de.herberlin.contact.default";
		} else if (obj instanceof Class) {
			loggerName = ((Class<Object>)obj).getName();
		} else {
			loggerName=obj.getClass().getName();
		}
		return Logger.getLogger(loggerName);
	}
}
